#include <windows.h>
#include "api.h"

#define buttonsClassName "BUTTONSWND"

typedef struct _BUTTONSWND_{
	int bx, by;
	int dx, dy;
	int cols;		// Nro of col buttons, to calculate the real index of the selected button
	HBITMAP bmp;
	UINT message;
	int selectedIndex;		// Button selected
} *PBUTTONSWND, BUTTONSWND;

void buttonsWndPaint(HWND hwnd, HDC pdc, PBUTTONSWND data)
{
	apiBitmap(pdc, data->bmp, 0, 0);
	if (data->selectedIndex<0){
		return;
	}
	// Draw the selected button
	RECT r;
	r.left = (data->selectedIndex % data->cols)*data->bx;
	r.top = (data->selectedIndex / data->cols)*data->by;
	r.right = r.left + data->bx;
	r.bottom = r.top + data->by;
	DrawEdge(pdc, &r, BDR_SUNKENINNER, BF_RECT);
}

void buttonsWndDestroy(HWND hwnd, PBUTTONSWND data){
	DeleteObject(data->bmp);
	FREE_DATA();
}

void buttonsWndLButtonUp(HWND hwnd, short x, short y, PBUTTONSWND data){
	int bx = x / data->bx;
	int by = y / data->by;
	int index = bx + (by*data->cols);
	HWND hParent = GetParent(hwnd);
	SendMessage(hParent, data->message, index, 0);
}

LRESULT CALLBACK buttonsWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam){
	GET_DATA(PBUTTONSWND);
	switch(message){
	case WM_PAINT:
		ON_PAINT(buttonsWndPaint);
		break;
	case WM_DESTROY:
		buttonsWndDestroy(hwnd, data);
		break;
	case WM_LBUTTONUP:
		buttonsWndLButtonUp(hwnd, LOWORD(lParam), HIWORD(lParam), data);
		break;
	}
	return DefWindowProc(hwnd, message, wParam, lParam);
}

PBUTTONSWND buttonsWndIniData(HINSTANCE hInstance, UINT idBmp, int buttondx, int buttondy, UINT message){
	HBITMAP hbmp = LoadBitmap(hInstance, MAKEINTRESOURCE(idBmp));
	BITMAP logBitmap;
	GetObject(hbmp, sizeof(BITMAP), &logBitmap);

	NEW_DATA(BUTTONSWND);

	data->dx = logBitmap.bmWidth;
	data->dy = logBitmap.bmHeight;

	data->bx = buttondx;
	data->by = buttondy;
	data->cols = data->dx / buttondx;
	data->bmp = hbmp;
	data->message = message;
	data->selectedIndex = -1;
	return data;
}

HWND buttonsWndCreate(HWND hwndParent, int x, int y, UINT idBmp, int buttondx, int buttondy, UINT message)
{
	static BOOLEAN isRegistered = FALSE;

	HINSTANCE hInstance = (HINSTANCE)GetWindowLong(hwndParent, GWL_HINSTANCE);

	if (!isRegistered){
		apiRegisterControlWnd(hInstance, buttonsClassName, buttonsWndProc);
		isRegistered = TRUE;
	}

	PBUTTONSWND data = buttonsWndIniData(hInstance, idBmp, buttondx, buttondy, message);

	HWND hwnd;
    hwnd = CreateWindowEx (0,
           buttonsClassName,
           "ageo - Minerva",
           WS_VISIBLE | WS_CLIPCHILDREN | WS_CHILD,
           x,
           y,
           data->dx,
           data->dy,
           hwndParent,
           NULL,
           hInstance,
		   data
           );
    ShowWindow (hwnd, SW_SHOW);
    return hwnd;
}

void buttonsSetSelected(HWND hwnd, int index){
	GET_PRIVATE_DATA(BUTTONSWND);
	data->selectedIndex = index;
	InvalidateRect(hwnd, NULL, FALSE);
}
